class Solution {
public:
    int search(vector<int>& nums, int target) 
    {
        int left = 0, right = nums.size() - 1;

        while(left <= right)
        {
            int mid = left + (right - left + 1) / 2;//防溢出

            if(nums[mid] > target)
                right = mid - 1;
            else if(nums[mid] < target)
                left = mid + 1;
            else 
                return mid;
        }
        return -1;
    }
};

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) 
    {
        //特殊处理
        if(nums.size() == 0) 
            return {-1,-1};

        int left = 0,right = nums.size() - 1;
        int begin = 0;

        //查找左端点
        while(left < right)
        {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target)//小于target说明目标值不可能存在
                left = mid + 1;
            else
                right = mid;
        }
        if(nums[right] != target)
            return {-1,-1};

        begin = left;
        //查找右端点
        right = nums.size() - 1;
        //重置right位置即可，因为已经求出左端点
        //所以不需要重置左端点
        while(left < right)
        {
            int mid = left + (right - left+ 1) / 2;
            if(nums[mid] <= target)
                left = mid; 
            else 
                right = mid - 1;
        }

        return {begin, left};
    }
};
